/*
 * LoginFilter.java
 *
 * Created on 10 de Julho de 2007, 11:11
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package br.usp.poli.mfc.struts.util;

import br.usp.poli.mfc.struts.bean.Usuario;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author William
 */
public class LoginFilter implements Filter {
    
    /** Creates a new instance of LoginFilter */
    public LoginFilter() {
        
    }

    public void init(FilterConfig filterConfig) throws ServletException {
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
            String login = "login.jsp"; // Pagina de login...
            String loggedout = "loggedout.jsp"; // Pagina de loggedout
            String loginAction = "Login.do";
            /* TODO: SE CRESCER MUITO AS PAGINAS DE EXCECAO, MELHOR PROCURAR NUMA AVLTREE OU HASH */
            HttpServletRequest req = (HttpServletRequest) request;
            HttpServletResponse res = (HttpServletResponse) response;
            HttpSession session = req.getSession();
            Usuario user = (Usuario)session.getAttribute("usuario");
            if(user == null && !req.getRequestURI().endsWith(login) && !req.getRequestURI().endsWith(loggedout) && !req.getRequestURI().endsWith(".css") && !req.getRequestURI().endsWith(loginAction) && !req.getRequestURI().endsWith(".png") && !req.getRequestURI().endsWith(".jpg") && !req.getRequestURI().endsWith(".jpeg") && !req.getRequestURI().endsWith(".gif")) {
                res.sendRedirect(login); //TODO: alterar aqui para pagina de login caso necessario
            } else {
                chain.doFilter(request,response);
            }
    }

    public void destroy() {
    }
    
}
